package com.inspection.service.impl;


import com.inspection.constant.ModelNameEnum;
import com.inspection.dao.FileDao;
import com.inspection.entity.FileDO;
import com.inspection.entity.InspectionBasicDO;
import com.inspection.model.dto.FileQueryDTO;
import com.inspection.service.FileService;
import com.inspection.support.FileUtil;
import com.inspection.support.PageHelper;
import com.inspection.support.model.BusinessBaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * @author : chenjx
 * create at:  2020/11/16  11:05 下午
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private FileDao fileDao;

    @Override
    public Long addFile(MultipartFile file,String modelName) {
        try {
            //上传到本地获取全路径
            if(modelName==null){
                modelName = ModelNameEnum.SYSTEM_FILE.getValue();
            }
            String realPath = FileUtil.uploadFile(modelName, file);
            //业务操作
            FileDO fileDO = new FileDO();
            fileDO.setFilePath(realPath);
            String[] split = file.getOriginalFilename().split("\\.");
            fileDO.setFileName(split[0]);
            fileDO.setFileType(split[1]);
            fileDO.setDateCreate(new Date());
            fileDO.setModelName(modelName);
//            SysUserDO sysUser = AuthHolder.getSysUser();
//            fileDO.setUploader_id(sysUser.getUser_id());
            return fileDao.saveAndFlush(fileDO).getId();
        } catch (Exception e) {
            log.error("上传文件失败，e={}",e);
            throw new BusinessBaseException("400","上传文件失败,请稍后再试！");
        }

    }


    @Override
    public Page<FileDO> pageFile(FileQueryDTO page) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        PageHelper check = PageHelper.check(page.getPageNo(), page.getPageSize());
        Pageable pageable = PageRequest.of(check.getOffset(), check.getPageSize(), sort);

        FileDO basicParam = new FileDO();
        basicParam.setModelName(page.getModelName());
        Page<FileDO> all = fileDao.findAll(Example.of(basicParam), pageable);
        try {
            all.get().forEach(fileDO -> {
                try {
                    fileDO.setModelNameDesc(ModelNameEnum.getByValue(fileDO.getModelName()).getDesc());
                } catch (Exception e) {
                    log.error("modelName error modelName = {}",fileDO.getModelName());
                }
            });
        } catch (Exception e) {
            log.error("转换异常");
        }
        return all;
    }
}
